#include <dirent.h>
#include <algorithm>
#include "browser.h"
#include "unicode.h"
#include "graphics.h"
#include "debug.h"

extern Graphics graphics;

// ---------------------------------------------------------------------------
void Browser::setPath(std::string newpath)
// ---------------------------------------------------------------------------
{
	path = newpath;
	fillList();
	selected = 0;
	drawLines();
	drawSelection();
}

// ---------------------------------------------------------------------------
void Browser::setPath(const char *newpath)
// ---------------------------------------------------------------------------
{
	path.assign(newpath);
	fillList();
	selected = 0;
	drawLines();
	drawSelection();
}

// ---------------------------------------------------------------------------
void Browser::drawLines()
// ---------------------------------------------------------------------------
{
	#ifndef DEBUG
	graphics.setBrowserLines(0, &filelist);
	#endif
}

// ---------------------------------------------------------------------------
void Browser::drawSelection()
// ---------------------------------------------------------------------------
{
	#ifndef DEBUG
	graphics.setBrowserHighlight(selected);
	#endif
}

// ---------------------------------------------------------------------------
void Browser::redraw()
// ---------------------------------------------------------------------------
{
	drawLines();
	drawSelection();	
}

// ---------------------------------------------------------------------------
void Browser::fillList()
// ---------------------------------------------------------------------------
{
	DIR *dir = opendir(path.data());
	dirent *entry;
	std::string filename;
	filelist.clear();
	if (dir != NULL)
	{
		while ((entry = readdir(dir)))
		{
			if (entry->d_name[0] != '.' && entry->d_name[1] != 0)
			{
				filelist.push_back( filename.assign(entry->d_name) );
			}
		}
		closedir(dir);
	}
	sort(filelist.begin(), filelist.end());
}

// ---------------------------------------------------------------------------
uint16_t Browser::getSelected()
// ---------------------------------------------------------------------------
{
	return selected;
}

// ---------------------------------------------------------------------------
std::string Browser::getEntry(uint16_t pos)
// ---------------------------------------------------------------------------
{
	if (pos >= filelist.size()) return "";
	return filelist[pos];
}

